import 'dart:developer' as developer;
import '../models/word.dart';
import '../services/database_service.dart';

class WordRepository {
  // 使用统一的数据库服务
  final DatabaseService _databaseService = DatabaseService();

  Future<int> addWord(Word word) async {
    try {
      developer.log('WordRepository: 添加单词: ${word.word}');
      
      // 检查单词是否已存在
      final existingWords = await getWordByText(word.word);
      if (existingWords.isNotEmpty) {
        developer.log('WordRepository: 单词已存在，不添加: ${word.word}');
        return existingWords.first.id!;
      }
      
      final wordMap = word.toMap();
      
      final id = await _databaseService.insert(
        DatabaseService.wordsTable,
        wordMap,
      );
      
      developer.log('WordRepository: 单词添加成功，ID: $id');
      return id;
    } catch (e) {
      developer.log('WordRepository: 添加单词失败: $e', error: e);
      // 返回-1表示添加失败，而不是重新抛出异常
      return -1;
    }
  }

  Future<List<Word>> getAllWords() async {
    try {
      developer.log('WordRepository: 获取所有单词');
      final results = await _databaseService.getAll(DatabaseService.wordsTable);
      
      return results.map((data) => Word.fromMap(data)).toList();
    } catch (e) {
      developer.log('WordRepository: 获取所有单词失败: $e', error: e);
      return [];
    }
  }
  
  Future<Word?> getWordById(int id) async {
    try {
      developer.log('WordRepository: 通过ID获取单词: $id');
      final data = await _databaseService.getById(DatabaseService.wordsTable, id);
      
      return data != null ? Word.fromMap(data) : null;
    } catch (e) {
      developer.log('WordRepository: 通过ID获取单词失败: $e', error: e);
      return null;
    }
  }
  
  Future<List<Word>> getWordByText(String text) async {
    try {
      developer.log('WordRepository: 通过文本获取单词: $text');
      List<Map<String, dynamic>> results;
      
      results = await _databaseService.getByField(
        DatabaseService.wordsTable,
        'word',
        text
      );
      
      return results.map((data) => Word.fromMap(data)).toList();
    } catch (e) {
      developer.log('WordRepository: 通过文本获取单词失败: $e', error: e);
      return [];
    }
  }

  Future<bool> updateWord(Word word) async {
    try {
      developer.log('WordRepository: 更新单词: ${word.word}');
      
      if (word.id == null) {
        developer.log('WordRepository: 更新失败，单词ID为空');
        return false;
      }
      
      final wordMap = word.toMap();
      
      developer.log('WordRepository: 使用数据库服务更新单词');
      final success = await _databaseService.update(
        DatabaseService.wordsTable,
        wordMap,
      );
      developer.log('WordRepository: 单词更新${success ? '成功' : '失败'}');
      return success;
    } catch (e) {
      developer.log('WordRepository: 更新单词失败: $e', error: e);
      return false;
    }
  }
  
  Future<bool> deleteAllWords() async {
    try {
      developer.log('WordRepository: 删除所有单词');
      await _databaseService.clearTable(DatabaseService.wordsTable);
      developer.log('WordRepository: 所有单词删除成功');
      return true;
    } catch (e) {
      developer.log('WordRepository: 删除所有单词失败: $e', error: e);
      return false;
    }
  }

  Future<bool> deleteWord(int id) async {
    try {
      developer.log('WordRepository: 删除单词，ID: $id');
      
      final success = await _databaseService.delete(
        DatabaseService.wordsTable,
        id,
      );
        developer.log('WordRepository: 单词删除${success ? '成功' : '失败'}');
        return success;
    } catch (e) {
      developer.log('WordRepository: 删除单词失败: $e', error: e);
      return false;
    }
  }

  Future<bool> clearAllWords() async {
    try {
      developer.log('WordRepository: 清空所有单词');
      
      final success = await _databaseService.clearTable(
        DatabaseService.wordsTable,
      );
      developer.log('WordRepository: 单词表清空${success ? '成功' : '失败'}');
      return success;
    } catch (e) {
      developer.log('WordRepository: 清空单词表失败: $e', error: e);
      return false;
    }
  }

  Future<int> getWordCount() async {
    try {
      developer.log('WordRepository: 获取单词数量');
      
      final count = await _databaseService.count(
        DatabaseService.wordsTable,
      );
      developer.log('WordRepository: 单词数量: $count');
      return count;
    } catch (e) {
      developer.log('WordRepository: 获取单词数量失败: $e', error: e);
      return 0;
    }
  }
  
  // 批量添加单词
  Future<int> addWords(List<Word> words) async {
    try {
      developer.log('WordRepository: 批量添加单词，数量: ${words.length}');
      
      int successCount = 0;
      for (final word in words) {
        final id = await addWord(word);
        if (id > 0) successCount++;
      }
      
      developer.log('WordRepository: 批量添加完成，成功: $successCount/${words.length}');
      return successCount;
    } catch (e) {
      developer.log('WordRepository: 批量添加单词失败: $e', error: e);
      return 0;
    }
  }
}